import { ListNode } from "./ListNode";

function reverseList(head: ListNode | null): ListNode | null {
  if (head === null || head.next === null) return head;

  let prev: ListNode | null = null;
  let current: ListNode | null = head;

  while (current !== null) {
    // 保存下一个节点
    const next = current.next as ListNode;
    // 反转指针方向
    current.next = prev;
    // 移动指针
    prev = current;
    current = next;
  }

  return prev; // 新头节点
}

const node1 = new ListNode(1);
node1.next = new ListNode(2);
node1.next.next = new ListNode(3);

const newHead = reverseList(node1);
let current: ListNode | null = newHead;
while (current) {
  console.log(current.val);
  current = current.next;
}

export {};
